import libtorrent as lt
import time

def download_magnet(magnet_link, save_path):
    # 创建会话
    ses = lt.session()
    ses.listen_on(6881, 6891)  # 设置监听端口范围

    # 添加磁力链接
    params = {
        'save_path': save_path,
        'storage_mode': lt.storage_mode_t.storage_mode_sparse,
        'paused': False,
        'auto_managed': True,
        'duplicate_is_error': True
    }

    handle = lt.add_magnet_uri(ses, magnet_link, params)
    ses.start_dht()

    print("正在下载元数据...")
    while not handle.has_metadata():
        time.sleep(1)

    print("开始下载: %s" % handle.name())
    
    # 显示下载进度
    while handle.status().state != lt.torrent_status.seeding:
        s = handle.status()
        print("\r%.2f%% 完成 (下载: %.1f kB/s 上传: %.1f kB/s peers: %d) %s" % (
            s.progress * 100, 
            s.download_rate / 1000, 
            s.upload_rate / 1000,
            s.num_peers,
            s.state),
            end=' ')
        time.sleep(1)

    print("\n下载完成！")

if __name__ == "__main__":
    magnet = "magnet:?xt=urn:btih:替换为实际哈希值&dn=文件名"
    save_dir = "./downloads"  # 保存路径
    
    download_magnet(magnet, save_dir)